<template>
    <div>
        <video ref="videoPlayer" controls></video>
        <div class="progress-bar-container">
            <input type="range" v-model="progress" :max="duration" :min="0" step="0.1" @input="onProgressInput" />
        </div>
    </div>
</template>

<script>
import Hls from "hls.js";

export default {
    data() {
        return {
            videoSrc: "http://localhost:8160/api/video/download/1886315717094641666/", // 后端返回的 .m3u8 文件的 URL
            progress: 0, // 当前播放进度
            duration: 0, // 视频总时长
        };
    },
    mounted() {
        const video = this.$refs.videoPlayer;

        // 检查 Hls.js 是否支持
        if (Hls.isSupported()) {
            const hls = new Hls();
            hls.loadSource(this.videoSrc);
            hls.attachMedia(video);

            // 监听 HLS 播放器的事件
            // hls.on(Hls.Events.MANIFEST_PARSED, () => {
            //     video.play();
            // });

            // 监听视频的时间更新事件
            video.addEventListener("timeupdate", this.updateProgress);
            video.addEventListener("loadedmetadata", this.setDuration);
        } else if (video.canPlayType("application/vnd.apple.mpegurl")) {
            video.src = this.videoSrc;
            video.addEventListener("loadedmetadata", this.setDuration);
            video.addEventListener("timeupdate", this.updateProgress);
            video.play();
        }
    },
    methods: {
        // 设置视频的总时长
        setDuration(event) {
            this.duration = event.target.duration;
        },

        // 更新播放进度
        updateProgress() {
            const video = this.$refs.videoPlayer;
            this.progress = video.currentTime;
        },

        // 用户拖动进度条时
        onProgressInput() {
            const video = this.$refs.videoPlayer;
            video.currentTime = this.progress;
        },
    },
};
</script>

<style scoped>
.progress-bar-container {
    margin-top: 10px;
    width: 100%;
    text-align: center;
}

input[type="range"] {
    width: 80%;
    height: 10px;
    -webkit-appearance: none;
    appearance: none;
    background: #ddd;
    border-radius: 5px;
    outline: none;
    transition: background 0.3s ease;
}

input[type="range"]::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 15px;
    height: 15px;
    background: #007bff;
    border-radius: 50%;
    cursor: pointer;
}

input[type="range"]::-moz-range-thumb {
    width: 15px;
    height: 15px;
    background: #007bff;
    border-radius: 50%;
    cursor: pointer;
}
</style>